<template>
  <div
    ref="dialogWrap"
    class="dialog_wrap"
  >
    <div
      ref="dialogBox"
      class="dialog_box"
    >
      <el-dialog
        v-model="dialogVisable"
        append-to-body
        :title="title"
        :class="`${customClass} ${visualThemeClassName} color-theme-editor-custom ${xvueNameSpace}`"
        :close-on-click-modal="false"
        top="12vh"
        @close="cancel"
      >
        <div class="color-type">
          <span>{{ $demoi18n('word.colorRender') }}：</span>
          <el-radio-group
            v-model="theme.colorType"
            @change="colorOptionChanged"
          >
            <el-radio label="single">{{ $demoi18n('panel.option.singleColor') }}</el-radio>
            <el-radio
              v-if="!form.ignore_customColorType_gradient"
              label="gradient"
            >{{
              $demoi18n('panel.colorEditor.gradient')
            }}</el-radio>
          </el-radio-group>
        </div>
        <div class="color-content-source">
          <el-radio-group
            v-model="theme.colorContentSource"
            @change="colorOptionChanged"
          >
            <el-radio-button label="original">{{ $demoi18n('word.packageColor') }}</el-radio-button>
            <el-radio-button
              v-if="hasCustom"
              label="custom"
            >{{ $demoi18n('word.customValueFieldColor') }}</el-radio-button>
          </el-radio-group>
        </div>
        <div class="color-theme-editor">
          <!--套餐 单色 single -->
          <el-table
            v-show="theme.colorType === SINGLE && theme.colorContentSource === ORIGINAL"
            class="config-panel-table"
            :data="theme.single_original_content"
            size="small"
            :max-height="tableMaxHeight"
          >
            <el-table-column
              :render-header="renderTableHeader"
              type="index"
              :label="$demoi18n('word.serialNumber')"
              :width="50"
              align="center"
            ></el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('word.choose')"
              :width="240"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <span>{{ scope.row[0] }}</span>
                  <el-color-picker
                    v-model="scope.row[0]"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    size="default"
                    color-format="hex"
                    append-to=".color-theme-editor-custom"
                  ></el-color-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('word.operation')"
              align="center"
            >
              <template #default="scope">
                <el-button
                  :link="true"
                  type="primary"
                  icon="Delete"
                  size="default"
                  :disabled="theme.single_original_content.length === 1"
                  @click="delColor('single_original_content', scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>
          <!--套餐 渐变色 gradient -->
          <el-table
            v-show="theme.colorType === GRADIENT && theme.colorContentSource === ORIGINAL"
            class="config-panel-table"
            :data="theme.gradient_original_content"
            size="small"
            :max-height="tableMaxHeight"
          >
            <el-table-column
              :render-header="renderTableHeader"
              type="index"
              :label="$demoi18n('word.serialNumber')"
              :width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('panel.colorEditor.startColor')"
              :width="60"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <el-color-picker
                    v-model="scope.row[0]"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    size="default"
                    color-format="hex"
                    append-to=".color-theme-editor-custom"
                  ></el-color-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('panel.colorEditor.endColor')"
              :width="60"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <el-color-picker
                    v-model="scope.row[1]"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    size="default"
                    color-format="hex"
                    append-to=".color-theme-editor-custom"
                  ></el-color-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('panel.colorEditor.preview')"
              align="center"
            >
              <template #default="scope">
                <div
                  class="gradient"
                  :style="getGradientStyle(scope.row)"
                ></div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :width="60"
              :label="$demoi18n('word.operation')"
              align="center"
            >
              <template #default="scope">
                <el-button
                  :link="true"
                  type="primary"
                  icon="Delete"
                  size="default"
                  :disabled="theme.gradient_original_content.length === 1"
                  @click="delColor('gradient_original_content', scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--自定义 单色 single -->
          <el-table
            v-show="theme.colorType === SINGLE && theme.colorContentSource === CUSTOM"
            class="config-panel-table"
            :data="theme.single_custom_content"
            size="small"
            :max-height="tableMaxHeight"
          >
            <el-table-column
              :render-header="renderTableHeader"
              type="index"
              :label="$demoi18n('word.serialNumber')"
              :width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('word.fieldValue')"
              :width="220"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <ValueInputer
                    v-model:value="scope.row.key"
                    :enum-values="enumValues"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('word.choose')"
              :width="240"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <span>{{ scope.row.color[0] }}</span>
                  <el-color-picker
                    v-model="scope.row.color[0]"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    size="default"
                    color-format="hex"
                    append-to=".color-theme-editor-custom"
                  ></el-color-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('word.operation')"
              align="center"
            >
              <template #default="scope">
                <el-button
                  :link="true"
                  type="primary"
                  icon="Delete"
                  size="default"
                  :disabled="theme.single_custom_content.length === 1"
                  @click="delColor('single_custom_content', scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <!--自定义 渐变色 gradient -->
          <el-table
            v-show="theme.colorType === GRADIENT && theme.colorContentSource === CUSTOM"
            class="config-panel-table"
            :data="theme.gradient_custom_content"
            size="small"
            :max-height="tableMaxHeight"
          >
            <el-table-column
              :render-header="renderTableHeader"
              type="index"
              :label="$demoi18n('word.serialNumber')"
              :width="55"
              align="center"
            ></el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('word.fieldValue')"
              :width="220"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <ValueInputer
                    v-model:value="scope.row.key"
                    :enum-values="enumValues"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('panel.colorEditor.startColor')"
              :width="60"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <el-color-picker
                    v-model="scope.row.color[0]"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    size="default"
                    color-format="hex"
                    append-to=".color-theme-editor-custom"
                  ></el-color-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('panel.colorEditor.endColor')"
              :width="60"
              align="center"
            >
              <template #default="scope">
                <div class="color">
                  <el-color-picker
                    v-model="scope.row.color[1]"
                    :popper-class="'vis-color-picker-panel-' + xvueTheme"
                    size="default"
                    color-format="hex"
                    append-to=".color-theme-editor-custom"
                  ></el-color-picker>
                </div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :label="$demoi18n('panel.colorEditor.preview')"
              align="center"
            >
              <template #default="scope">
                <div
                  class="gradient"
                  :style="getGradientStyle(scope.row.color)"
                ></div>
              </template>
            </el-table-column>
            <el-table-column
              :render-header="renderTableHeader"
              :width="60"
              :label="$demoi18n('word.operation')"
              align="center"
            >
              <template #default="scope">
                <el-button
                  :link="true"
                  type="primary"
                  icon="Delete"
                  size="default"
                  :disabled="theme.gradient_custom_content.length === 1"
                  @click="delColor('gradient_custom_content', scope.row)"
                ></el-button>
              </template>
            </el-table-column>
          </el-table>

          <div class="add_color">
            <el-button
              class="btn-sure"
              type="primary"
              icon="CirclePlus"
              size="default"
              @click="addColor"
            >{{ $demoi18n('btn.add') }}</el-button>
          </div>
        </div>
        <template #footer>
          <span>
            <el-button
              class="button-cancel"
              @click="cancel"
            >{{ $demoi18n('btn.cancel') }}</el-button>
            <el-button
              class="btn-sure"
              type="primary"
              :disabled="theme.colors.length === 0"
              @click="save"
            >{{
              $demoi18n('btn.confirm')
            }}</el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>
<script lang='jsx'>
import ValueInputer from '@/components/common/value-inputer/value-inputer.vue';
import { dropArrItem, getLightColor } from '@/utils/util.js';
import { mapState } from 'vuex';

const SINGLE = 'single';
const GRADIENT = 'gradient';
const ORIGINAL = 'original';
const CUSTOM = 'custom';
const COLORLEVEL = 0.8; // 颜色变亮系数 0-1
function getEmptyThemeConf() {
  return {
    componentStyle: '', // light | dark
    type: '', // single | gradient,
    key: '', // t20200907173055021

    /*
     * 单色：['#fdb61a', '#00acff', '#5ecc49']
     * 渐变色： [ ['#0de396', '#5ecc49'], ['#ff7800', '#d46325'], ['#fff68f', '#efe147'] ]
     */
    colors: [],
  };
}

export default {
  components: { ValueInputer },
  inject: {
    ColorThemeEditorCustom: {
      default: () => ({
        hasCustom: true,
      }),
    },
    panelWid: {
      default: '',
    },
  },
  props: {
    config: Object, // 组件的全部配置
    form: Object, // 对应具体组件的property
    visible: Boolean,
    themeConf: {
      type: Object,
      default: () => getEmptyThemeConf(),
    },
    enumPrikey: String, // 自定义颜色主题下拉选择字段名
  },
  emits: ['save', 'cancel'],
  data() {
    return {
      xvueNameSpace: process.env.xvueNameSpace, // 给挂载在body下的元素加上主类名
      xvueTheme: window._adoPremise.uc.theme, // 'dark',
      customClass: `color_theme_dialog color_theme_dialog-${window._adoPremise.uc.theme || 'light'}`,
      dialogVisable: this.visible,
      theme: getEmptyThemeConf(),

      tableMaxHeight: 450,
      SINGLE,
      GRADIENT,
      ORIGINAL,
      CUSTOM,
      colorType: SINGLE,
      colorContentSource: ORIGINAL, // original|custom
      hasCustom: true, // 是否显示自定义颜色主题选项
    };
  },
  computed: {
    ...mapState({
      panelApiDatas: state => state.VisualComponentsModule.panelApiDatas,
    }),
    title() {
      return this.$demoi18n('panel.colorEditor.customColorPackage');
    },
    enumValues() {
      let arr = [];
      let pKeys = '';
      if (this.enumPrikey) {
        pKeys = this.enumPrikey;
      } else {
        const { customColorField } = this.config.config && this.config.config.property;
        if (customColorField) {
          pKeys = customColorField;
        }
      }
      pKeys = pKeys ? pKeys.split(',') : [];

      this.panelApiDatas[this.panelWid].forEach(n => {
        pKeys.forEach(key => {
          arr.push(n[key]);
        });
      });
      arr = Array.from(new Set(arr));
      const options = arr.map(n => ({ label: n, value: n }));
      return options;
    },
  },
  watch: {
    themeConf() {
      this.initTheme();
    },
    visible(val) {
      this.dialogVisable = val;
      if (val) {
        setTimeout(() => {
          // 在this.initTheme() 后面执行
          this.initColorData();
        }, 10);
      }
    },
    dialogVisable(val) {
      // 需要将弹窗放在body下，不然会被其他组件挡住
      if (val) {
        this.initTheme();
      }
    },
  },
  created() {
    this.initExtraConf();
  },
  methods: {

    // 初始化自定义值下拉项
    initColorData() {
      // 最后一次的数据配置
      let lastColorData;
      if (this.form.colorData) {
        lastColorData = JSON.parse(JSON.stringify(this.form.colorData));
      }
      const isSameConfig = this.checkSameConfig({
        lastColorData,
        colorData: this.config.config.data,
      });
      if (!isSameConfig) {
        this.theme['gradient_custom_content'] = [];
        this.theme['single_custom_content'] = [];
        this.colorOptionChanged();
      }
    },

    // 检查dataSourceType,apiCode,tableData等相关数据是否相同
    checkSameConfig({ lastColorData, colorData }) {
      let isSameConfig = false;
      if (!lastColorData) {
        return false;
      }
      const { apiCode, tableData, dataSourceType, dataPackage } = lastColorData;
      const flag = (dataSourceType === colorData.dataSourceType) &&
                  (apiCode === colorData.apiCode || dataPackage === colorData.dataPackage) &&
                  tableData.length;
      if (flag) {
        let isSameTableData = true;
        const tableDataNow = colorData.tableData || [];

        for (let index = 0; index < tableData.length; index++) {
          const item = tableData[index];

          const findSameOne = tableDataNow.find(t => item.field === t.field && item.mapping === t.mapping);
          if (!findSameOne) {
            isSameTableData = false;
            break;
          }
        }
        if (isSameTableData) {
          isSameConfig = true;
        }
      }
      return isSameConfig;
    },

    // 选项改变时，根据数组长度默认赋值
    colorOptionChanged() {
      const { theme } = this;
      if (theme.colorContentSource === CUSTOM) {
        // 数组为空
        if (!theme[`${theme.colorType}_${theme.colorContentSource}_content`].length) {
          this.addColor();
        }
      }
    },
    initTheme() {
      const form = this.$attrs.form || this.form || {};
      if (!form.colorComponents || form.colorComponents !== 'ColorThemeEditorCustom') {
        return;
      }
      const _themeConf = JSON.parse(JSON.stringify(this.themeConf));
      if (_themeConf.type === SINGLE) {
        // 需要转换成数组，不然 v-model="scope.row" 不起作用
        _themeConf.colors = _themeConf.colors.map(n => [n]);
      }

      // 单色值的转换
      _themeConf['single_original_content'] = _themeConf.single_original_content.map(n => [n]);

      _themeConf.colors.forEach(n => {
        for (let i = 0; i < n.length; i++) {
          n[i] = n[i].toUpperCase(n[i]);
        }
      });
      this.theme = _themeConf;

      // 新属性初始赋值
      this.theme.colorType = this.theme.colorType || this.theme.type || SINGLE;
      this.theme.colorContentSource = this.theme.colorContentSource || ORIGINAL;

      // 将colors 赋值到 single_original_content 或者 gradient_original_content
      if (_themeConf.colorContentSource === ORIGINAL) {
        const colorContent = _themeConf[`${_themeConf.type}_${_themeConf.colorContentSource}_content`];
        if (!colorContent.length) {
          _themeConf[`${_themeConf.type}_${_themeConf.colorContentSource}_content`] = _themeConf.colors;
        }
      }

      // 没有单色套餐，由现有的渐变套餐取值，形成套餐
      const { single_original_content: singles } = _themeConf;
      const { gradient_original_content: gradients } = _themeConf;
      if (!singles.length) {
        gradients.forEach(item => {
          singles.push([item[0]]);
        });
      }

      // 没有渐变套餐，由现有的单色套餐取值，形成套餐
      if (!_themeConf.gradient_original_content.length) {
        singles.forEach(item => {
          gradients.push([item[0], getLightColor(item[0], COLORLEVEL)]);
        });
      }
    },
    delColor(content, color) {
      this.theme[content] = dropArrItem(this.theme[content], color);
    },
    addColor() {
      const { theme } = this;
      const color = theme.colorType === SINGLE ? ['#DDDDDD'] : ['#DDDDDD', '#DDDDDD'];
      if (theme.colorContentSource === ORIGINAL) {
        this.theme[`${theme.colorType}_${theme.colorContentSource}_content`].push(color);
      } else {
        this.theme[`${theme.colorType}_${theme.colorContentSource}_content`].push({
          key: '',
          color,
        });
      }
    },
    getGradientStyle(color) {
      return {
        backgroundImage: `linear-gradient(to right, ${color[0]}, ${color[1]})`,
      };
    },
    cancel() {
      this.$emit('cancel');
    },

    // 单色值数组的转换
    convertColor(colorArr) {
      const _colorArr = colorArr.map(n => n[0]);
      return _colorArr;
    },
    save() {
      if (!this.theme.colors.length) {
        return;
      }

      const _themeConf = JSON.parse(JSON.stringify(this.theme));
      if (this.theme.type === 'single') {
        _themeConf.colors = _themeConf.colors.map(n => n[0]);
      }

      // 单色的转换
      _themeConf['single_original_content'] = this.convertColor(_themeConf.single_original_content);

      const { apiCode, tableData, dataSourceType, dataPackage } = this.config.config.data;
      this.form.colorData = {
        apiCode,
        tableData,
        dataSourceType,
        dataPackage,
      };
      this.$emit('save', _themeConf);
    },
    renderTableHeader({ column }) {
      return (
        <el-tooltip placement="top" content={column.label} effect={this.xvueTheme}>
          <span>{column.label}</span>
        </el-tooltip>
      );
    },
    initExtraConf() {
      const conf = this.ColorThemeEditorCustom;
      if (conf) {
        Object.entries(conf).map(([i]) => {
          this[i] = conf[i];
        });
      }
    },
  },
};
</script>
<style lang="less">
@import '../../../common/color-picker-panel.less';
</style>
<style lang="less">
.color_theme_dialog {
  width: 650px;
  :deep(.cell) {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
</style>
<style lang="less" scoped>
.color-type {
  margin-bottom: 10px;
  margin-left: 12px;
}
.color-content-source {
  margin-left: 8px;
}

.color-theme-editor {
  .row {
    display: flex;
    align-items: center;
    .label {
      width: 80px;
      text-align: left;
    }
    .cont {
      display: flex;
    }
  }
  .el-table {
    margin-top: 20px;
    width: 100%;
    border: 1px solid #ddd;
    .color {
      display: flex;
      align-items: center;
      justify-content: center;
      span {
        margin-right: 5px;
        width: 70px;
      }
    }
    .gradient {
      width: 100%;
      height: 26px;
    }
  }
  .add_color {
    display: flex;
    margin-top: 20px;
  }
  .bottom_btns {
    display: flex;
    justify-content: center;
    margin-top: 30px;
    .save {
      margin-left: 40px;
    }
  }
}
</style>

<style lang="less">
@font_color_dark: #98cae6;
@font_color_active_dark: #00f0ff;
@background_color_dark: #071f30;
@bgColor_dark: #000c17;
@borderColor_dark: #116584;
@textColor_dark: #ffffff;

.color_theme_dialog-dark {
  :deep(.el-dialog__header) {
    background: #183c5a;
    .el-dialog__title {
      font-size: 16px;
      color: #fff;
    }

    .el-dialog__headerbtn .el-dialog__close {
      color: #fff;
    }
  }

  .el-dialog__body {
    color: #98cae6;
    background: #0e2b40;

    .color-theme-editor {
      background: #0e2b40;
      // 表格
      .config-panel-table {
        color: @font_color_dark;
        background-color: @background_color_dark;
        border-color: #116584 !important;
        &::before {
          background-color: @background_color_dark;
        }

        .cell {
          padding: 0 3px !important;
        }
        td,
        th {
          padding: 5px 0 !important;
        }

        .el-table__header {
          th {
            background-color: #122b40 !important;
            border-color: #122b40;
            color: @font_color_dark;
          }
        }

        .el-table__body {
          tr {
            td {
              background-color: @background_color_dark;
              border-color: @background_color_dark;

              .el-color-picker__trigger {
                border-color: #116584;
                .el-color-picker__color {
                  border-color: #116584;
                }
                .el-color-picker__icon {
                  color: #116584;
                }
              }
              .icon-library-open {
                background-color: unset;
                border-color: #0eb4c2;
              }
            }
          }
        }

        .el-table__empty-block {
          background-color: #093758;

          .el-table__empty-text {
            color: @font_color_active_dark;
          }
        }
      }
      .el-form-item__label {
        color: @font_color_dark;
      }
      .el-form-item__content {
        .el-input {
          .el-input__inner {
            border-color: @borderColor_dark;
            color: @textColor_dark;
            background-color: @bgColor_dark;
          }

          .el-input__icon {
            color: @borderColor_dark;
          }
        }

        .el-radio-group {
          .el-radio {
            color: @textColor_dark;

            .el-radio__input {
              .el-radio__inner {
                border-color: @font_color_active_dark;
                background-color: unset;
              }
            }

            .is-checked {
              .el-radio__inner {
                &::after {
                  background-color: @font_color_active_dark;
                }
              }
            }

            .el-radio__label {
              color: #fff;
            }
          }
        }
      }
    }
  }

  :deep(.el-dialog__footer) {
    color: #606266;
    background: #0e2b40;
  }

  // 默认按钮样式类
  .btn-sure {
    background-color: #0eb4c2;
    border-color: #0eb4c2;
    color: #fff;

    .el-icon-circle-plus {
      color: #fff;
    }
  }

  .button-cancel {
    background-color: #064559;
    border-color: #064559;
    color: #fff;

    .el-icon-circle-plus {
      color: #fff;
    }
  }
}
</style>
